import dayjs, { Dayjs } from "dayjs";
import { httpGetAsync, httpPost } from "../../autox/http";
import { $, toSecond, updateFloat } from "../../utils";
import { IScheduleTask } from "../node";
import { RedPacket } from "./RedPacket";
declare const runtime: any;

export class KwaiNebulaZhaoBaoSheduleTask implements IScheduleTask {
    time: number = 1000 * 60 * 30;
    title: string = `【快手极速抓包】`;
    isRuning: boolean = false;
    check(): boolean {
        if (this.redPackets.length === 0) {
            return true;
        }
        if (this.redPackets.find(red => [6, 2, 0].includes(red.type))) {
            return false;
        }
        return true;
    }
    start(): void {
        if (this.isRuning) {
            updateFloat({ toast: `${this.title}已经执行` })
            return;
        }
        this.isRuning = true;
        this.openKsLive()
        updateFloat({ toast: `正在执行${this.title}任务`, currentTask: this.title })
        sleep(1000 * 10)
        this.joinRedPacket()
    }
    openKsLive(signal: boolean = true) {
        let flag: any = signal ? Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK : Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK;
        const uri = `ksnebula://liveaggregatesquare`
        const intent = app.intent({
            action: "android.intent.action.VIEW",
            data: uri,
            flags: flag
        });
        context.startActivity(intent);
    }
    private maxTime: number = 20 * 1000;
    private isNotRoom() {
        const root = selector().visibleToUser(true).findOne()
        let result: number = 0;
        this.filterEachChildren(root, (node) => {
            if (!node) return false;
            const id = node?.id();
            const text = node?.text() || ''
            if (text.includes(`直播已结束`)) {
                result = 1;
                return false;
            }
            if (text.includes(`领取并使用`)) {
                result = 0;
                return false;
            }
            if (text.includes(`立即关注`)) {
                result = 0;
                return false;
            }
            if (text === `首页`) {
                result = 3;
                return false;
            }
            if (!id) return false;
            if (id.endsWith(`live_red_packet_status_text`)) {
                result = 2
                return false;
            };
            if (id.endsWith(`live_audience_count_text`)) {
                this.online = parseInt(text)
                result = 2
                return false;
            }
            if (id.endsWith(`live_anchor_avatar_icon`)) {
                result = 2
                return false;
            }
            if (id.endsWith(`live_anchor_avatar_icon`)) {
                result = 2
                return false;
            }
            return false;
        })
        return result
    }
    online: number = 0;
    openTime: Dayjs;
    failCount: number = 0;
    count: number = 0;
    redCount: number = 0;
    /**
        const latestActivity = runtime.info.latestActivity;
        log(`${latestActivity}`)
        if (['zd4.q', 'n27.a', 'u27.a', 'gqc.a', 'com.kuaishou.live.basic.dialog.LiveDialogContainerFragment$b'].includes(latestActivity)) {
            back();
            sleep(2000)
        }
     */
    private joinRedPacket() {
        if ($.getCurrentPackageName() !== $.PACKAGES["com.kuaishou.nebula"]) {
            sleep(1000 * 3)
            return false;
        }
        sleep(1000)
        const isNotRoom = this.isNotRoom()
        log(`is not room ${isNotRoom}`)
        if (isNotRoom === 1) {
            return this.toNext();
        }
        if (isNotRoom === 0) {
            if ($.getCurrentPackageName() !== $.PACKAGES["com.kuaishou.nebula"]) {
                sleep(1000 * 3)
                return false;
            }
            if (this.failCount > 3) {
                this.failCount = 0;
                return false;
            }
            this.failCount + 1;
            back();
            sleep(3000)
            this.joinRedPacket()
            return;
        }
        if (isNotRoom === 3) {
            return;
        }
        let time = new Date().getTime()
        updateFloat({ currentResult: `正在检查房间状态` })
        const node = selector().idEndsWith("live_red_packet_status_text").visibleToUser(true).findOne(this.maxTime)
        this.maxTime = ((new Date().getTime() - time) + this.maxTime) / 2;
        this.openTime = dayjs()
        const second = toSecond(node?.text());
        this.openTime = this.openTime.add(second, 'second')
        this.count += 1;
        if (node) {
            $.tryClickButton(node)
            updateFloat({ currentResult: `成功打开红包弹框`, nebulaTodayCount: `${this.redCount}/${this.count}` })
            this.joinAndWaitRedPacket()
        } else {
            this.maxTime + 1000;
            updateFloat({ currentResult: `此房间暂无红包，正在进入下一个房间`, nebulaTodayCount: `${this.redCount}/${this.count}` })
        }
        return this.toNext();
    }
    private toNext() {
        updateFloat({ currentResult: `正在进入下一个房间` })
        if ($.getCurrentPackageName() !== $.PACKAGES["com.kuaishou.nebula"]) {
            sleep(1000 * 3)
            return false;
        }
        this.redPackets = [];
        this.online = 0;
        this.openTime = null;
        $.swipeUp()
        this.joinRedPacket()
    }
    redPackets: RedPacket[] = [];
    private joinAndWaitRedPacket() {
        const viewPager = selector().classNameEndsWith('ViewPager').visibleToUser(true).findOne(15 * 1000)
        if(!viewPager) return;
        const children = viewPager.children()
        let joinCount: number = 0;
        for (let index = 0; index < children.length; index++) {
            const child = children[index];
            let texts: string[] = [];
            const redPacket = new RedPacket();
            this.filterEachChildren(child, (node) => {
                let text = node?.text()
                const id = node?.id();
                if (id) {
                    if (id.endsWith('action_view')) {
                        redPacket.setJoinButton(node)
                    }
                }
                if (text) {
                    texts.push(text)
                    if (text === `开金粉 抢红包`) {
                        redPacket.setJoinButton(node)
                    }
                    if (text === `去评论`) {
                        redPacket.setJoinButton(node)
                    }
                    if (text === `抢红包`) {
                        redPacket.setJoinButton(node)
                    }
                    if (text === `点我抢红包`) {
                        redPacket.setJoinButton(node)
                    }
                }
                return false;
            })
            redPacket.setText(texts.join(' '))
            if (redPacket.join(false)) {
                joinCount += 1;
                this.redPackets.push(redPacket)
            }
        }
        back();
        sleep(1000 * 3)
        if (joinCount > 0) {
            this.redCount += 1;
            httpPost('addRedPkg', {
                redPackets: this.redPackets,
                ...this.getShareLink(),
                online: this.online,
                openTime: this.openTime.format('YYYY-MM-DD HH:mm:ss')
            }).catch(e => { })
            updateFloat({ currentResult: `已抓到${joinCount}个红包，正在上传`, nebulaTodayCount: `${this.redCount}/${this.count}` })
        } else {
            updateFloat({ currentResult: `没有满足条件的红包` })
        }
    }
    private getShareLink() {
        const more = selector().id("live_bottom_bar_single_icon_container").visibleToUser(true).findOne(1000 * 15)
        $.clickButton(more);
        const share = selector().id("live_bottom_bar_item_title_text_view").text(`分享`).visibleToUser(true).findOne(1000 * 15)
        $.clickButton(share);
        const copy = selector().text(`复制链接`).visibleToUser(true).findOne(1000 * 15)
        $.clickButton(copy);
        sleep(1000)
        const link = getClip()
        if (link) {
            const res = link.match(/(http.*?) (.*?)的直播/)
            if (res && res.length > 0) {
                const link = res[1]
                const name = res[2]
                const shareLink = this.getRealLink(link)
                return {
                    name,
                    originLink: link,
                    ...shareLink,
                }
            }
        }
        return {}
    }

    private getRealLink(link: string) {
        const response = httpGetAsync(link)
        const url = response?.url.toString() as string;
        const [path, query] = url.split(`?`)
        const res = path.match(/fw\/live\/(.*)/)
        if (res && res.length > 0) {
            const [, ksid] = res;
            const params: any = {}
            query.split('&').map(key => {
                const [name, value] = key.split('=');
                params[name] = value;
            });
            return { ...params, ksid, originUrl: link };
        }
        return {}
    }
    private filterEachChildren(node: UiObject, filter: (node: UiObject) => boolean) {
        if (!node) return [];
        const children = node.children();
        const list: UiObject[] = [];
        children.map(child => {
            if (filter(child)) {
                list.push(child)
            } else {
                list.push(...this.filterEachChildren(child, filter))
            }
        });
        return list;
    }
    stop(): void {
        this.isRuning = false;
        this.redPackets = [];
        updateFloat({ toast: `${this.title}任务执行结束`, currentTask: this.title, currentResult: `任务结束` })
        this.toHome();
    }
    toHome(time: number = 3) {
        if ($.getCurrentPackageName() !== $.PACKAGES["com.kuaishou.nebula"]) {
            sleep(1000 * 3)
            return false;
        }
        let homeNode = selector().text('首页').visibleToUser(true).findOne(3000)
        while (!homeNode && time > 0) {
            time -= 1;
            back();
            sleep(3000)
            $.tryClickButton(selector().textMatches('退出直播间|退出').findOne(3000))
        }
    }
}